package com.zz.tijian.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.easysdk.factory.Factory;
import com.zz.tijian.config.AliPayConfig;
import com.zz.tijian.entity.Orders;
import com.zz.tijian.entity.req.CancelOrderDto;
import com.zz.tijian.entity.req.CheckAvailabilityDto;
import com.zz.tijian.entity.req.PayOrderDto;
import com.zz.tijian.entity.req.PlaceOrderDto;
import com.zz.tijian.entity.res.AvailabilityVo;
import com.zz.tijian.entity.res.OrderDetailVo;
import com.zz.tijian.entity.res.OrderOfSetmealVO;
import com.zz.tijian.entity.res.Result;
import com.zz.tijian.expections.BadRequestException;
import com.zz.tijian.handle.mq.RefundProducer;
import com.zz.tijian.handle.pay.res.AlipayStrategy;
import com.zz.tijian.service.OrdersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "order-预约相关接口")
@RestController
@RequestMapping("/order")
@CrossOrigin
@Slf4j
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private AlipayStrategy alipayStrategy;
    @Autowired
    private AliPayConfig aliPayConfig;

    @ApiOperation("用户下单预约")
    @PostMapping("/placeOrder")
    public Result<OrderDetailVo> placeOrder(@RequestBody PlaceOrderDto placeOrderDto){
        return ordersService.placeOrder(placeOrderDto);
    }
    @ApiOperation("/用户支付-阿里支付")
    @PostMapping("/ali")
    public Result<Object> payOrderAli(@RequestBody PayOrderDto payOrderDto){
        return ordersService.payOrder(payOrderDto,alipayStrategy);
    }

    @ApiOperation("/用户支付-其他支付,暂时没有实现")
    @PostMapping("/other")
    public Result<Object> payOrderOther(@RequestBody PayOrderDto payOrderDto){
        throw new BadRequestException("暂时还没有上线哦,敬请期待");
        /*return ordersService.payOrder(payOrderDto,alipayStrategy);*/
    }


    @GetMapping(value = "/returnUrl")
    public void returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = String.join(",", values);
            // 解决乱码
            valueStr = new String(valueStr.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            params.put(name, valueStr);
        }

        String alipayPublicKey = aliPayConfig.getALIPAY_PUBLIC_KEY();
        String charset = aliPayConfig.getCHARSET();
        String signType = aliPayConfig.getSIGN_TYPE();
        log.info("支付宝返回参数: {}", params);
        boolean signVerified = AlipaySignature
                .rsaCheckV1(params,alipayPublicKey,charset ,signType); // 调用SDK验证签名

        //验证签名（支付宝公钥）
        if (signVerified) {
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no")
                    .getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no")
                    .getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount")
                    .getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

            log.info("商户订单号: {}", out_trade_no);
            log.info("支付宝交易号: {}", trade_no);
            log.info("付款金额: {}", total_amount);

            // 支付成功，修改支付状态
            ordersService.paySuccess(Integer.parseInt(out_trade_no));

            response.sendRedirect("http://localhost:5173/appointmentSuccess?status=true&msg=支付成功");
        } else {
            response.sendRedirect("http://localhost:5173/appointmentSuccess?status=false&msg=支付发生了错误!");
        }
    }

    @GetMapping("/checkAvailability")
    @ApiOperation("查询套餐余量")
    public Result<AvailabilityVo>  checkAvailability(CheckAvailabilityDto checkAvailabilityDto) {

        return ordersService.checkAvailability(checkAvailabilityDto);

    }
    @GetMapping("/selectOrder")
    @ApiOperation("查询用户所有预约订单")
    public Result<List<OrderOfSetmealVO>> selectOrderByUserId(){
        return ordersService.selectOrderByUserId();
    }
    @GetMapping("/selectByOrderId/{orderId}")
    @ApiOperation("查询单个预约订单详情")
    public Result<OrderDetailVo> selectByOrderId(@PathVariable Integer orderId){

        return ordersService.selectByOrderId(orderId);
    }
    @ApiOperation("取消预约/退款")
    @PostMapping("/cancel")
    public Result<Boolean> cancelOrder(@RequestBody CancelOrderDto cancelOrderDto){

        return ordersService.cancelOrder(cancelOrderDto);
    }

    @Autowired
    private RefundProducer refundProducer;
    @GetMapping
    public void test(){
        refundProducer.sendRefundMessage(1);
    }

}
